<template>
  <div class="agent-contact">
    <!-- 按钮模式 -->
    <el-button 
      v-if="mode === 'button'" 
      :type="buttonType"
      :size="buttonSize"
      @click="showContactCard = true"
    >
      <slot>联系经纪人</slot>
    </el-button>

    <!-- 卡片模式 -->
    <div v-else-if="mode === 'card'" class="contact-card">
      <contact-card 
        :agent="agentInfo" 
        :house-id="houseId"
        :show-appointment="showAppointment"
        @start-chat="onStartChat"
      />
    </div>

    <!-- 联系弹窗 -->
    <el-dialog
      v-model="showContactCard"
      title="联系经纪人"
      width="420px"
      destroy-on-close
      :show-close="true"
      class="agent-contact-dialog"
    >
      <contact-card 
        :agent="agentInfo" 
        :house-id="houseId"
        :show-appointment="showAppointment"
        @start-chat="onStartChat"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import ContactCard from './components/ContactCard.vue'
import { useUserStore } from '@/stores/user'
import { useLoginStore } from '@/stores/login'
import { getAgentInfo } from '@/api/agent' // 直接导入API函数

const props = defineProps({
  // 经纪人ID
  agentId: {
    type: [Number, String],
    default: null
  },
  // 房源ID (用于预约看房)
  houseId: {
    type: [Number, String],
    default: null
  },
  // 显示模式: 'button' 或 'card'
  mode: {
    type: String,
    default: 'button',
    validator: (value) => ['button', 'card'].includes(value)
  },
  // 按钮类型
  buttonType: {
    type: String,
    default: 'primary'
  },
  // 按钮大小
  buttonSize: {
    type: String,
    default: 'default'
  },
  // 经纪人数据 (如果提供，则不会发起请求)
  agentData: {
    type: Object,
    default: () => ({})
  },
  // 是否显示预约看房按钮
  showAppointment: {
    type: Boolean,
    default: true
  },
  // 经纪人姓名
  agentName: {
    type: String,
    default: ''
  },
  // 经纪人电话
  agentPhone: {
    type: String,
    default: ''
  },
  // 经纪人微信
  agentWechat: {
    type: String,
    default: ''
  }
})

// 定义事件
const emit = defineEmits(['start-chat'])

const userStore = useUserStore()
const loginStore = useLoginStore()
const router = useRouter()
const showContactCard = ref(false)

// 经纪人信息
const agentInfo = ref({
  id: null,
  name: '',
  title: '',
  avatar: '',
  phone: '',
  wechat: '',
  wechatQrCode: '',
  chatUserId: null,
  userId: null
})

// 是否已登录
const isLoggedIn = computed(() => userStore.isLoggedIn)

// 获取经纪人信息
const fetchAgentInfo = async () => {
  // 确保有效的经纪人ID
  if (!props.agentId) {
    console.warn('未提供经纪人ID，将使用默认数据');
    // 设置默认值，避免UI显示错误
    agentInfo.value = {
      id: null,
      name: '暂无经纪人',
      title: '房产顾问',
      avatar: '/src/assets/images/default-avatar.png',
      phone: '',
      wechat: '',
      wechatQrCode: '',
      chatUserId: null,
      userId: null
    }
    return;
  }

  try {
    console.log('获取经纪人信息, 经纪人ID:', props.agentId);
    // 直接调用API函数获取经纪人信息
    const response = await getAgentInfo(props.agentId);
    console.log('获取经纪人信息响应:', response);
    
    if (response && response.code === 200 && response.data) {
      const agentData = response.data;
      
      // 获取聊天用户ID，可能来自各种字段
      const chatUserId = agentData.userId || agentData.user_id || agentData.chatUserId;
      
      agentInfo.value = {
        id: agentData.agentId || props.agentId,
        name: agentData.realName || '未知经纪人',
        title: agentData.position || agentData.title || '房产顾问',
        avatar: agentData.avatar || '/src/assets/images/default-avatar.png',
        phone: agentData.phone || agentData.mobile || '',
        wechat: agentData.wechat || '',
        wechatQrCode: agentData.wechatQrCode || '',
        // 保存聊天用户ID
        chatUserId: chatUserId,
        userId: chatUserId
      }
      
      // 如果没有获取到聊天用户ID，尝试通过专门的API获取
      if (!chatUserId) {
        try {
          const { getAgentUserId } = await import('@/api/agent');
          const userIdRes = await getAgentUserId(props.agentId);
          if (userIdRes.code === 200 && userIdRes.data) {
            const userId = userIdRes.data.userId || userIdRes.data.user_id || userIdRes.data;
            console.log('通过API获取到的用户ID:', userId);
            agentInfo.value.chatUserId = userId;
            agentInfo.value.userId = userId;
          }
        } catch (userIdError) {
          console.error('获取经纪人用户ID失败:', userIdError);
          // 如果获取失败，使用经纪人ID作为默认值
          agentInfo.value.chatUserId = props.agentId;
        }
      }
      
      console.log('处理后的经纪人信息:', agentInfo.value);
    } else {
      throw new Error(response?.msg || '获取经纪人信息失败');
    }
  } catch (error) {
    console.error('获取经纪人信息失败:', error)
    ElMessage.error('获取经纪人信息失败')
    // 设置默认值，避免UI显示错误
    agentInfo.value = {
      id: props.agentId,
      name: '未知经纪人',
      title: '房产顾问',
      avatar: '/src/assets/images/default-avatar.png',
      phone: '',
      wechat: '',
      wechatQrCode: '',
      chatUserId: null,
      userId: null
    }
  }
}

// 处理开始聊天事件
const handleStartChat = () => {
  // 触发父组件的事件
  emit('start-chat')
}

// 处理ContactCard组件的聊天事件
const onStartChat = () => {
  // 隐藏弹窗
  showContactCard.value = false
  
  // 触发父组件的事件
  emit('start-chat')
}

// 初始化
onMounted(async () => {
  // 如果有agentData或单独的属性，不需要获取经纪人信息
  const hasProvidedData = Object.keys(props.agentData).length > 0 || 
                          (props.agentName || props.agentPhone || props.agentWechat);
  
  // 只有当提供了经纪人ID且没有提供经纪人数据时，才需要获取经纪人信息
  if (props.agentId && !hasProvidedData) {
    console.log('需要获取经纪人详情，agentId:', props.agentId);
    await fetchAgentInfo();
  } else if (hasProvidedData) {
    console.log('已提供经纪人数据，无需获取');
    // 使用提供的数据初始化
    if (Object.keys(props.agentData).length > 0) {
      agentInfo.value = {
        id: props.agentId,
        ...props.agentData
      }
    } else {
      agentInfo.value = {
        id: props.agentId,
        name: props.agentName,
        phone: props.agentPhone,
        wechat: props.agentWechat
      }
    }
  }
})
</script>

<style lang="scss" scoped>
.agent-contact {
  display: inline-block;
}

.contact-card {
  border-radius: 12px;
  overflow: hidden;
}

/* 弹窗样式优化 */
:deep(.agent-contact-dialog) {
  .el-dialog__header {
    padding: 16px 20px;
    margin: 0;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .el-dialog__body {
    padding: 0;
  }
  
  .el-dialog__headerbtn {
    font-size: 18px;
  }
}
</style> 